package com.hc.mall.product.exception;

import com.hc.common.exception.BizCodeEnum;
import com.hc.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@Slf4j
//@ControllerAdvice(basePackages = "com.hc.mall.product.controller")
//@ResponseBody //响应JSON数据
@RestControllerAdvice(basePackages = "com.hc.mall.product.controller") //等价于@ControllerAdvice+@ResponseBody
public class MallGlobalAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class) //接收哪些异常类型
    public R handleValidException(MethodArgumentNotValidException e){
        log.error("数据校验出现问题{}，异常类型：{}",e.getMessage(),e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        Map<String,String> map = new HashMap<>();
        bindingResult.getFieldErrors().forEach(item->{
            String field = item.getField();
            String message = item.getDefaultMessage();
            map.put(field,message);
        });
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(),BizCodeEnum.VALID_EXCEPTION.getMessage()).put("data",map);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable e){
        log.error("出现问题{}，异常类型：{}",e.getMessage(),e.getClass());
        return R.error(BizCodeEnum.UNKHOW_EXCEPTION.getCode(),BizCodeEnum.UNKHOW_EXCEPTION.getMessage());
    }
}
